package mblog.core.persist.service.impl;

import mblog.base.email.EmailSender;
import mblog.core.data.Mail;
import mblog.core.persist.dao.MailDao;
import mblog.core.persist.entity.MailPO;
import mblog.core.persist.service.MailService;
import mblog.core.persist.utils.BeanMapUtils;
import mtons.modules.pojos.Paging;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Project  : mblog
 * Author   : Wu Tian Qiang
 * Date     : 2016/7/13
 */
@Service
@Transactional
public class MailServiceImpl implements MailService {
    @Autowired
    private MailDao mailDao;
    @Autowired
    private EmailSender emailSender;

    @Override
    public void save(String[] qqs) {
        for (String qq : qqs) {
            MailPO mailPO = new MailPO();
            qq = qq.trim();
            mailPO.setMail(qq + "@qq.com");
            mailPO.setQq(qq);
            mailDao.saveOrUpdate(mailPO);
        }
    }

    @Override
    public void paging(Paging paging) {
        List<MailPO> list = mailDao.paging(paging);
        List<Mail> rets = new ArrayList<>();
        list.forEach(po -> {
            rets.add(BeanMapUtils.copy(po));
        });
        paging.setResults(rets);
    }

    @Override
    public void sendMail(Integer sendAmount, String receiveMail, String subject, String content) {
        List<String> receiveMails = new ArrayList<>();
        if (sendAmount > 0) {
            List<MailPO> mailPOs = mailDao.findMail(sendAmount);
            for (MailPO mailPO : mailPOs) {
                receiveMails.add(mailPO.getMail());
            }
        }
        if (!"".equals(receiveMail)) {
            receiveMails.addAll(Arrays.asList(receiveMail.split(";")));
        }
        for (String mail : receiveMails) {
            if (!"".equals(mail)) {
                emailSender.sendText(mail, subject, content, true);
                mailDao.updateSendAmount(mail);
            }
            try {
                Thread.sleep(1000 * 10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
